//
//  XSStatusListViewModel.swift
//  WeiDo
//
//  Created by XISHAN on 16/3/6.
//  Copyright © 2016年 XISHAN. All rights reserved.
//

import UIKit
import SDWebImage

class XSStatusListViewModel: NSObject {

    //当前视图模型(ViewModel)对应的模型(model)
    var statusArray:[XSStatusViewModel]?
    
    func loadData(isPullUp: Bool , complete:(isSuccess: Bool) -> ()){
        
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        var max_ID :Int64 = 0
        var since_ID :Int64 = 0
        if isPullUp{
            max_ID = statusArray?.last?.status?.id ?? 0
            if max_ID != 0{
                max_ID--
            }
        }else{
            since_ID = statusArray?.first?.status?.id ?? 0
        }
        
        let parameters = [
        "access_token" : XSUserAccountViewModel.sharedAccountViewModel.accessToken!,
        "max_id" : "\(max_ID)",
        "since_id":"\(since_ID)"
        ]
        
        XSNetworkTools.sharedXSNeworkTool.request(.GET, urlString: url, parameters: parameters) { (responseObjc , error) -> () in
            if error != nil{
                print("主页信息获取错误:\(error)")
                complete(isSuccess: false)
                return
                
            }
            print("获取当前登录用户及其所关注（授权）用户的最新微博:\(responseObjc)")
            
            //获取用户及其关注用户的微博数据 进行字典转模型
            let dicts = responseObjc!["statuses"] as! [[String : AnyObject]]
            
            var tempArray = [XSStatusViewModel]()
            for dict in dicts{
                let status = XSStatus.init(dict: dict)
                let viewModel = XSStatusViewModel(status:status)
                tempArray.append(viewModel)
            }
            if self.statusArray == nil{
                self.statusArray = [XSStatusViewModel]()
            }
            
            if isPullUp{
                //上拉加载更多之前的数据就把数据加到后面
                self.statusArray! = self.statusArray! + tempArray
            }else{
                
                //下拉刷新就把数据在到前面
                self.statusArray! = tempArray + self.statusArray!
            }
            
            
            // 缓存单张图片
            self.cacheSingleImage(tempArray,complete: complete)
            //complete(isSuccess: true)
            
            //self.tableView.reloadData()
        }
        
    }
    
    private func cacheSingleImage(viewModels: [XSStatusViewModel],complete: (isSuccess: Bool)->()){
        
        // 调度组
        let group = dispatch_group_create()
        let queue = dispatch_get_main_queue()
        // 2. 循环调用下载图片的方法
        
        for viewModel in viewModels {
            // 1. 拿到url?????
            // 先取到原创微博的配图地址
            var urls = viewModel.status?.pic_urls
            // 判断如果地址为nil 或者 urls的count 为0,那么就直接设置取转发微博配图
            if urls == nil || urls!.count == 0 {
                urls = viewModel.status?.retweeted_status?.pic_urls
            }
            
            
            // 判断 urls 是否只有一张图片,如果只有一张图片,就去下载图片
            if urls?.count == 1 {
                guard let urlString = urls?.first?.thumbnail_pic else {
                    continue
                }
                
                // 做入组操作
                dispatch_group_enter(group)
                // 下载图片
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString), options: [], progress: nil, completed: { (image, error, _, _, url) -> Void in
                    print("下载完成,地址是:\(url.absoluteString)")
                    // 下载完成或者下载失败
                    dispatch_group_leave(group)
                })
            }
        }
        // 3. 图片下完成之后回调给界面让界面去刷新数据
        dispatch_group_notify(group, queue) { () -> Void in
            print("所有单张图片都下载完成")
            complete(isSuccess: true)
        }
    }

}
